﻿
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using LibSars;

namespace SarsClient
{
	/// <summary>
	/// Class to do handshake
	/// with other peers.
	/// </summary>
	public class PeerConnector
	{
		#region Class members
		
		/// <summary>
		/// Reference on ConnectionManager for
		/// Peer Management.
		/// </summary>
		ConnectionManager cmgr;	
		
		#endregion
		
		#region Public methods
		
		/// <summary>
		/// Connect to IP Address on specific port.
		/// </summary>
		/// <param name="p_ipAddr">IP Address.</param>
		/// <param name="p_port">Port.</param>
		public void Connect(IPAddress p_ipAddr, int p_port){
			new Thread(delegate(){
			    //TcpClient tcpClient = new TcpClient();
				//tcpClient.Connect(new IPEndPoint(p_ipAddr,1580));

				try {
					Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
					                           ProtocolType.Tcp);
					socket.Connect(new IPEndPoint(p_ipAddr,p_port));
					SarsPacket outPkg = new SarsPacket();
					outPkg.Message = new SarsPacketMessageIMINURCHAT();
					outPkg.SenderId = cmgr.OwnId;
					outPkg.RecipientId = 0x0000;
					
					socket.Send(outPkg.GenerateBytes());
					Thread.Sleep(Global.SettingConnectWait); // Wait before receive
					
					byte[] buffer = new byte[2048];
					socket.Receive(buffer);
					
					SarsPacket[] packets = SarsPacketByteArrayExtractor.GetAllPackets(buffer);
					if (packets.Length > 0){
			
						SarsPacket inPkg = packets[0];
						if (inPkg.Message.GetMTypeInt() == SarsPacketMessageIMINURCHAT.MTypeInt){
		
							Peer peer = new Peer(inPkg.SenderId, cmgr.OwnId, socket);
					
							cmgr.AddPeer(peer);
							return ; // Return to prevent socket close
						}
						
					}
				} catch { }
				
			}).Start();
		}
		#endregion
		
		#region Constructors
		public PeerConnector(ConnectionManager p_cmgr){
			cmgr = p_cmgr;
		}
		#endregion
	}
}
